package controllers

import (
	"fmt"
	"github.com/robfig/cron"
	"math"
	"WDserver/config"
	"WDserver/models"
	"WDserver/util"
)

var NewID int

func PaoDian () {
	if config.Config().PdStart == false{
		return
	}

	fmt.Println("正在开启泡点。。。")
	StartID()
	c := cron.New()
	spec := "0 0 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 * * ?"
	c.AddFunc(spec, func() {
		go Traversing()
	})
	c.Start()
	select{}

}


func StartID() {
	a := new(models.LoginLog)
	has, _ := models.LDB.Desc("id","login_mode").Get(a)
	if has == false{
		fmt.Println("暂无记录，ID值已重置为1。")
	}
	if a.LoginMode == 0 {
		NewID = a.Id + 1
	} else {
		NewID = a.Id
	}
	fmt.Println("ID获取成功！ID:",NewID)
}

func Traversing (){
	b := new(models.LoginLog)
	rows, err := models.LDB.Where("id >=?", NewID).Rows(b)
	if err != nil {
		fmt.Println("查询账号失败！")
	}
	defer rows.Close()
	for rows.Next() {
		err = rows.Scan(b)
		Used := aa(b.TimeUsed)
		if b.LoginMode == 1 {
			continue
		} else if Used == 0 {
			continue
		}else {
			func() {
				UpdateCoin(b.Account, Used)
			}()
		}

	}
	StartID()
}

func UpdateCoin (account string,used int) {
	a := new(models.Account)
	has, _ := models.ADB.ID(account).Get(a)
	if has == false {
		fmt.Printf("错误：账号%s不存在！\n",account)
		return
	}
	jyb := config.Config().Pjyb * used
	yyb := config.Config().Pyyb * used
	a.GoldCoin = a.GoldCoin + jyb
	a.SilverCoin = a.SilverCoin + yyb
	if a.GoldCoin > 2000000000 {
		fmt.Println("金元宝数量已到达上限无法兑现！账号：",account)
		return
	}
	if a.SilverCoin > 2000000000 {
		fmt.Println("银元宝数量已到达上限无法兑现！账号：",account)
		return
	}
	check := util.Checksum(a.Account, a.Password, a.Privilege, a.GoldCoin, a.SilverCoin)
	a.Checksum = check
	_, err1 := models.ADB.ID(a.Account).Update(a)
	if err1 != nil{
		fmt.Println("错误：兑换失败！")
		return
	}
	fmt.Printf("本轮泡点兑换成功！账号：%s,本轮获得金元宝：%d,本轮获得银元宝：%d。\n",account,jyb,yyb)

}

func aa(i int)int{
	a := float64(i)
	b := a/60.0
	x := math.Floor(b + 0.5)
	return int(x)
}
